#include "joystick.h"


//引脚定义,电路板遥杆横置，X、Y反向
unsigned char joystick_x;  // y轴
unsigned char joystick_y; // x轴

/*********************
 * ----初始化
*********************/
void joystick::Init(unsigned char Pin1,unsigned char Pin2)//X、Y
{
  joystick_x = Pin1;
  joystick_y = Pin2;

  pinMode(joystick_x,INPUT);
  pinMode(joystick_y,INPUT);
  //pinMode(joystick_z,INPUT);
}

/*********************************
 * 读取数据与传感器数据优化-防抖
*********************************/
int joystick::Read_xyz(String joystick_xyz)
{
  int X,Y,Z,X_0,Y_0,Z_0;//X_0为原始读取值，X为最终输出值,xy互换

  if (joystick_xyz == "X轴")
  {
    X_0 = analogRead(joystick_y);//xy互换
    if ( ( X_0 > 480 ) and ( X_0 < 543 ) )//不同传感器中间值不同，优化防抖
    {
      X = 0;
    }
    else if ( X_0 < 10 )
    {
      X = -100;
    }
    else if ( X_0 > 1013 )
    {
      X = 100;
    }
    else
    {
      X = map(X_0, 0, 1023, -100, 100);
    }
    return X;
  }

  else if (joystick_xyz == "Y轴")
  {
    Y_0 = analogRead(joystick_x);
    if ( ( Y_0 > 480 ) and ( Y_0 < 543 ) )//不同传感器中间值不同，优化防抖
    {
      Y = 0;
    }
    else if ( Y_0 < 10 )
    {
      Y = 100;
    }
    else if ( Y_0 > 1013 )
    {
      Y = -100;
    }
    else
    {
      Y = map(Y_0, 0, 1023, 100, -100);
    }
    return Y;
  }
 /* 
  else if (joystick_xyz == "Z轴")
  {
    Z = !digitalRead(joystick_z); 
    return Z;
  }
  */
}
